<template>
  <div>
    <h2>{{ isAdd ? '添加文章' : '修改文章' }}</h2>
    <input type='file' id="selectFilePath" @change="fileChange" ref="uploadRef" style="display: none;" />
    <div class="selectBox">
      <el-select v-model="data.articleType" placeholder="请选择">
        <el-option v-for="item in typeList" :key="item._id" :label="item.typeName" :value="item._id">
        </el-option>
      </el-select>
      <el-date-picker @change="dateChange" v-model="data.createTime" type="datetime" placeholder="Select date and time">
      </el-date-picker>
    </div>
    <el-input placeholder="标题" v-model="data.title" clearable>
    </el-input>
    <el-input placeholder="描述" v-model="data.describe" clearable>
    </el-input>
    <el-input v-model="imageName" disabled autocomplete="off" placeholder="请选择文章封面图">
    <template #append>
      <el-icon class="uploadIcon"  @click="selectFile('image')"><upload-filled /></el-icon>
      <el-icon class="deleteIcon" @click="clearFile('image')"><delete-filled /></el-icon>
      </template>
    </el-input>

    <el-input v-model="musicName" disabled autocomplete="off" placeholder="请选择文章背景音乐">
    <template #append>
      <el-icon class="uploadIcon"  @click="selectFile('music')"><upload-filled /></el-icon>
      <el-icon class="deleteIcon" @click="clearFile('music')"><delete-filled /></el-icon>
      </template>
    </el-input>
    <div ref='editor' id="div1">
    </div>
    <el-button type="primary" @click="submit">保存</el-button>
  </div>
</template>

<script>
  import {
    toRefs,
    ref,
    reactive,
    onMounted,
    onBeforeUnmount
  } from 'vue'
  import {
    useRoute,
    useRouter
  } from 'vue-router'
  import {
    findArticle,
    findArticleType,
    addArticle,
    editArticle,
    uploadFile
  } from '../../plugins/request'
  import WangEditor from 'wangeditor'
  import dayjs from 'dayjs'
  import { UploadFilled, DeleteFilled } from '@element-plus/icons'
  import { ElMessage, ElMessageBox} from 'element-plus'
  export default {
    components: {
      UploadFilled,
      DeleteFilled
    },
    setup() {
      const editor = ref();
      const state = reactive({
        typeList: [{
          typeName: '请选择',
          _id: ''
        }],
        value: '',
        isAdd: null,
        data: {
          title: '',
          wordsNum: null,
          content: '',
          articleType: '',
          describe: '',
          createTime: '',
          image: {
            url: '',
            name: ''
          },
          music: {
            url: '',
            name: ''
          }
        },
        id: '',
        html: '',
        text: '',
        imageName: '',
        musicName: '',
        uploadType: ''
      })
      let instance;
      const route = useRoute()
      const router = useRouter()
      onMounted(() => {
        state.id = route.query.id || ''
        state.id ? state.isAdd = false : state.isAdd = true
        findAllType()
        state.id && inIdFindArticle()
        instance = new WangEditor(editor.value);
        instance.config.zIndex = 500
        Object.assign(instance.config, {
          onchange() {
            //console.log('change');
          },
        });
        instance.create();
      })
      onBeforeUnmount(() => {
        instance.destroy();
        instance = null;
      });
      const inIdFindArticle = async () => {
        let data = await findArticle({
          'id': state.id
        })
        state.data = data.data.data
        state.data.articleType = state.data.articleType._id
        instance.txt.html(state.data.content)
      }
      const findAllType = async () => {
        let {
          data
        } = await findArticleType({})
        if (data.status != 1) return
        state.typeList = data.data.data
      }
      const dateChange = e => {
        console.log(e)
        state.data.createTime = dayjs(e).format('YYYY-DD-HH hh:mm:ss')
      }
      const submit = async () => {
        let html = instance.txt.html()
        let temp = html.replace(/<\/?.+?>/g, "");
        let result = temp.replace(/ /g, "");
        state.data.content = html
        state.data.wordsNum = result.length
        // let date = new Date()
        // let time = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
        const map = {
          'articleType': '请选择文章类型',
          'title': '请输入标题',
          'content': '请输入文章内容'
        }
        for (let i in map) {
          if (!state.data[i]) {
            ElMessage.error(map[i])
          }
        }
        let {
          data
        } = state.isAdd ? await addArticle(state.data) : await editArticle(state.data)
        if (data.status == 1) {
          ElMessage.success('操作成功')
          router.go(-1)
        } else {
          ElMessage.error('操作失败')
        }
      }
      const syncHTML = () => {
        state.html = instance.txt.html();
      };
      let uploadRef = ref(null)
      const selectFile = type => {
        state.uploadType = type
        uploadRef.value.click()
      }
      const fileChange = async () => {
        let file = uploadRef.value.files[0]
        let allowType = []
        if(state.uploadType == 'image') {
          allowType = ['image/jpeg', 'image/png']
        }else{
          allowType = ['audio/mpeg']
        }
        if(!allowType.includes(file.type)) return ElMessage.warning('文件格式不合法')
        let patams = new FormData()
        patams.append('file', file)
        let res = await uploadFile(patams)
        if(res.data.status == 1) {
          if(state.uploadType == 'image') {
            state.imageName = file.name
            //state.data.image = res.data.data
          }else{
            state.musicName = file.name
            //state.data.music = res.data.data
          }
        }else{
          ElMessage.error('上传文件失败')
        }
      }
      const clearFile = type => {
        if(type == 'image') {
            state.imageName = ""
            state.data.image = {
              url: '',
              name: ''
            }
          }else{
            state.musicName = ""
            state.data.music = {
              url: '',
              name: ''
            }
          }
      }
      return {
        ...toRefs(state),
        syncHTML,
        editor,
        submit,
        dateChange,
        selectFile,
        fileChange,
        clearFile,
        uploadRef
      }
    }
  }
</script>

<style lang="scss" scoped>
  h2 {
    height: 49px;
  }

  ::v-deep {
    //下拉列表的内容不在该页面容器，无法修改样式
    // .el-popper{
    //   z-index: 200000!important;
    // }
    //文本编辑器z-index可以配置无需强行改css
    // .w-e-toolbar{
    //   z-index: 1001!important;
    // }
    // .w-e-text-container{
    //   z-index: 1000!important;
    // }
  }

  .el-input {
    margin-top: 20px;
  }

  #div1 {
    margin: 20px 0;
  }
  .selectBox{
    display: flex;
    justify-content: space-between;
  }
  .uploadIcon{
    cursor: pointer;
    margin-right: 10px;
  }
  .deleteIcon {
    cursor: pointer;
  }
</style>